﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>新增客户</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        body {
            padding: 15px;
            background-color: #f5f5f5;
            margin: 0;
            height: 100vh;
            overflow: hidden;
        }
        .form-container {
            background-color: white;
            padding: 15px;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            height: calc(100vh - 30px);
            overflow-y: auto;
        }
        .required {
            color: red;
        }
        .layui-form-item {
            margin-bottom: 12px;
        }
        .layui-form-label {
            padding: 6px 15px;
            width: 90px;
        }
        .layui-input, .layui-select, .layui-textarea {
            height: 32px;
            line-height: 32px;
        }
        .layui-textarea {
            height: 60px;
            resize: none;
        }
        .form-buttons {
            text-align: center;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e6e6e6;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <form class="layui-form" id="addCustomerForm" lay-filter="addCustomerForm">
            @* 重新启用防伪标记，这是必需的 *@
            @Html.AntiForgeryToken()
            <!-- 第一行：客户编码、客户名称、客户简称 -->
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户编码 <span class="required">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="customerCode" required lay-verify="required" placeholder="请输入客户编码" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户名称 <span class="required">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="customerName" required lay-verify="required" placeholder="请输入客户名称" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户简称</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerShortName" placeholder="请输入客户简称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第二行：客户类型、客户电话、联系人 -->
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户类型 <span class="required">*</span></label>
                        <div class="layui-input-block">
                            <select name="customerType" required lay-verify="required">
                                <option value="">请选择客户类型</option>
                                <option value="企业客户">企业客户</option>
                                <option value="个人客户">个人客户</option>
                                <option value="政府客户">政府客户</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户电话</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerPhone" placeholder="请输入客户电话" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">联系人</label>
                        <div class="layui-input-block">
                            <input type="text" name="contactPerson" placeholder="请输入联系人" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第三行：联系人电话、是否启用、客户英文名称 -->
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">联系人电话</label>
                        <div class="layui-input-block">
                            <input type="text" name="contactPhone" placeholder="请输入联系人电话" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">是否启用</label>
                        <div class="layui-input-block">
                            <input type="radio" name="isActive" value="true" title="是" checked>
                            <input type="radio" name="isActive" value="false" title="否">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md4">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户英文名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerEnglishName" placeholder="请输入客户英文名称" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第四行：备注 -->
            <div class="layui-row">
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea name="remark" placeholder="请输入备注信息" class="layui-textarea"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 按钮 -->
            <div class="form-buttons">
                <button type="button" class="layui-btn" lay-submit lay-filter="submitAddCustomer">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelAddCustomer">取消</button>
                <button type="button" class="layui-btn layui-btn-warm" id="testControllerBtn" style="margin-left: 10px;">测试控制器</button>
            </div>
        </form>
    </div>

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer'], function () {
            var form = layui.form;
            var layer = layui.layer;

            // 表单提交事件
            form.on('submit(submitAddCustomer)', function (data) {
                var formData = data.field;

                // 表单验证
                if (!formData.customerCode) {
                    layer.msg('请输入客户编码');
                    return false;
                }
                if (!formData.customerName) {
                    layer.msg('请输入客户名称');
                    return false;
                }
                if (!formData.customerType) {
                    layer.msg('请选择客户类型');
                    return false;
                }

                // 构建提交数据对象，匹配后端CustomerModel
                // 注意：数据库中所有字段都是必填的，需要提供空字符串而不是null
                var customerData = {
                    CustomerCode: formData.customerCode || '',
                    CustomerName: formData.customerName || '',
                    CustomerNiciname: formData.customerShortName || '', // 注意：后端字段名是CustomerNiciname
                    CustomerType: formData.customerType || '',
                    CustomerPhone: formData.customerPhone || '',
                    CustomerIsTrue: formData.isActive === 'true' // 转换为boolean
                };

                // 详细调试信息
                console.log('原始表单数据:', formData);
                console.log('提交的客户数据:', customerData);
                console.log('CustomerIsTrue值:', customerData.CustomerIsTrue, '类型:', typeof customerData.CustomerIsTrue);
                
                // 添加防伪令牌
                var token = $('input[name="__RequestVerificationToken"]').val();
                if (token) {
                    customerData.__RequestVerificationToken = token;
                }
                
                // 提交数据
                layer.load(1, { shade: [0.3, '#000'] });

                // 发送新增请求 - 使用表单数据格式（支持防伪令牌）
                var possibleUrls = [
                    '/Customer/AddCustomer',
                    '/ProductionSystem/Customer/AddCustomer'
                ];
                
                var currentUrlIndex = 0;
                var currentMethod = 'urlencoded'; // 'urlencoded' 或 'formdata'
                
                function trySubmit() {
                    var currentUrl = possibleUrls[currentUrlIndex];
                    console.log('尝试URL:', currentUrl, '方法:', currentMethod);
                    
                    var ajaxOptions = {
                        url: currentUrl,
                        type: 'POST',
                        dataType: 'text',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        success: function(result) {
                            layer.closeAll('loading');
                            console.log('提交成功，URL:', currentUrl, '方法:', currentMethod, '返回值:', result);
                            
                            // 根据接口返回值判断：1=成功，0=失败
                            if (result === 1 || result === "1") {
                                // 通知父窗口刷新数据并显示成功消息
                                if (parent && parent.loadCustomerData) {
                                    parent.loadCustomerData('新增客户成功！');
                                }
                                // 关闭弹窗
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            } else {
                                layer.msg('新增客户失败，请检查数据后重试', {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求失败 [' + currentUrl + '][' + currentMethod + ']:', xhr.status, xhr.responseText);
                            
                            // 如果当前方法失败，尝试另一种方法
                            if (currentMethod === 'urlencoded' && (xhr.status === 400 || xhr.status === 405)) {
                                currentMethod = 'formdata';
                                console.log('尝试FormData方法...');
                                trySubmit();
                                return;
                            }
                            
                            // 如果是404或405错误，尝试下一个URL
                            if ((xhr.status === 404 || xhr.status === 405) && currentUrlIndex < possibleUrls.length - 1) {
                                currentUrlIndex++;
                                currentMethod = 'urlencoded'; // 重置方法
                                console.log('尝试下一个URL...');
                                trySubmit();
                                return;
                            }
                            
                            // 所有URL都失败了，显示错误
                            layer.closeAll('loading');
                            var errorMsg = '新增客户失败';
                            var responseText = xhr.responseText || '';
                            
                            if (xhr.status === 400) {
                                errorMsg = '请求参数错误：' + responseText;
                            } else if (xhr.status === 404) {
                                errorMsg = '接口地址不存在，请检查路由配置';
                            } else if (xhr.status === 405) {
                                errorMsg = '请求方法不被允许，可能是防伪令牌问题';
                            } else if (xhr.status === 500) {
                                errorMsg = '服务器内部错误，请联系管理员';
                            } else if (xhr.status === 0) {
                                errorMsg = '网络连接失败，请检查网络';
                            }
                            
                            layer.msg(errorMsg + ' (状态码: ' + xhr.status + ')', {
                                icon: 2,
                                time: 5000
                            });
                        }
                    };
                    
                    // 根据当前方法设置数据和Content-Type
                    if (currentMethod === 'formdata') {
                        // 使用FormData对象
                        var formData = new FormData();
                        Object.keys(customerData).forEach(function(key) {
                            formData.append(key, customerData[key]);
                        });
                        ajaxOptions.data = formData;
                        ajaxOptions.processData = false;
                        ajaxOptions.contentType = false;
                    } else {
                        // 使用URL编码格式
                        ajaxOptions.data = customerData;
                        ajaxOptions.contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
                    }
                    
                    $.ajax(ajaxOptions);
                }
                
                // 开始尝试提交
                trySubmit();

                return false;
            });

            // 取消按钮事件
            $('#cancelAddCustomer').on('click', function () {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            });

            // 测试控制器按钮事件
            $('#testControllerBtn').on('click', function () {
                testControllerAccess();
            });

            // 添加测试函数，验证控制器访问
            function testControllerAccess() {
                layer.msg('正在测试控制器访问...', { time: 1000 });
                
                // 尝试多种可能的路由
                var routes = [
                    '/Customer/CustomerQuerys',
                    '/ProductionSystem/Customer/CustomerQuerys', 
                    '/Customer'
                ];
                
                routes.forEach(function(url, index) {
                    setTimeout(function() {
                        $.ajax({
                            url: url,
                            type: 'GET',
                            timeout: 5000,
                            success: function(result) {
                                console.log('路由测试成功 [' + url + ']:', result);
                                layer.msg('控制器访问成功: ' + url, { icon: 1 });
                            },
                            error: function(xhr, status, error) {
                                console.error('路由测试失败 [' + url + ']:', xhr.status, error);
                                if (index === routes.length - 1) {
                                    layer.msg('所有路由测试完成，请查看控制台', { icon: 2 });
                                }
                            }
                        });
                    }, index * 1000);
                });
            }
        });
    </script>
</body>
</html>